package cn.itcast.hotel.service.impl;

import cn.itcast.hotel.mapper.HotelMapper;
import cn.itcast.hotel.pojo.Hotel;
import cn.itcast.hotel.pojo.HotelDoc;
import cn.itcast.hotel.pojo.RequestParam;
import cn.itcast.hotel.service.IHotelService;
import cn.itcast.hotel.util.ResponseHandler;
import cn.itcast.hotel.vo.PageResult;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpHost;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.geo.GeoPoint;
import org.elasticsearch.common.unit.DistanceUnit;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.index.query.functionscore.WeightBuilder;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.sort.SortBuilder;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class HotelService extends ServiceImpl<HotelMapper, Hotel> implements IHotelService {
    private Map<String,List<String>> map = new HashMap<>();
    private List<String> brand = new ArrayList<>();
    private List<String> city = new ArrayList<>();
    private List<String> starName = new ArrayList<>();

    @Autowired
    private RestHighLevelClient client;

    @Override
    public PageResult search(RequestParam param) {
        PageResult pageResult=null;
        SearchRequest request = new SearchRequest("hotel");
        String key = param.getKey();
        String city = param.getCity();
        String brand = param.getBrand();
        String starName = param.getStarName();
        String location = param.getLocation();
        Integer maxPrice = param.getMaxPrice();
        Integer minPrice = param.getMinPrice();
        Integer page = param.getPage();
        Integer size = param.getSize();
        // 创建布尔查询，判断匹配条件
        BoolQueryBuilder builder = new BoolQueryBuilder();
        if (key == null || "".equals(key)){
            builder.must(QueryBuilders.matchAllQuery());
        }else {
            builder.must(QueryBuilders.matchQuery("name",key));
        }
        if (city != null && !"".equals(city)){
            builder.filter(QueryBuilders.termQuery("city",city));
        }
        if (brand != null && !"".equals(brand)){
            builder.filter(QueryBuilders.termQuery("brand",brand));

        }
        if (starName != null && !"".equals(starName)){
            builder.filter(QueryBuilders.termQuery("starName",starName));
        }
        if (maxPrice != null){
            builder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice));
        }
        if (minPrice != null){
            builder.filter(QueryBuilders.rangeQuery("price").gte(minPrice));
        }
        if (location != null && !"".equals(location)){
            request.source().sort(SortBuilders
                    .geoDistanceSort("location",new GeoPoint(location))
                    .unit(DistanceUnit.KILOMETERS).order(SortOrder.ASC));
        }
        // 设定算分排序权重
        WeightBuilder weightBuilder = ScoreFunctionBuilders.weightFactorFunction(15);
        // 创建算分排序查询器
        FunctionScoreQueryBuilder functionScoreQueryBuilder =
//                参数一为布尔查询器
                QueryBuilders.functionScoreQuery(builder,
//                        参数二为算分查询器
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
//                              加权对象为设定的match对象
                                new FunctionScoreQueryBuilder.FilterFunctionBuilder(QueryBuilders.matchQuery("isAD", true), weightBuilder)});
        request.source().query(functionScoreQueryBuilder);
//        分页
        request.source().from((page-1)*size).size(size);
//        排序
        if ("score".equals(param.getSortBy())){
            request.source().sort("score",SortOrder.DESC);
        }else if ("price".equals(param.getSortBy())){
            request.source().sort("price",SortOrder.ASC);
        }
//        设置高亮
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.preTags("<em>");
        highlightBuilder.postTags("</em>");
        highlightBuilder.field("name").requireFieldMatch(false);
        request.source().highlighter(highlightBuilder);
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            pageResult = ResponseHandler.responseHandle(response);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            return pageResult;
        }

    }

    @Override
    public Map<String, List<String>> filters(RequestParam param) {
        map.clear();
        brand.clear();
        city.clear();
        starName.clear();

        try {
            brand = getBrand(param);
            city = getCity(param);
            starName = getStarName(param);
            map.put("brand",brand);
            map.put("city",city);
            map.put("starName",starName);
        } catch (IOException e) {
            e.printStackTrace();
            log.warn("错误原因为{}",e.getMessage());
        }
        return map;
    }

    @Override
    public void indexHotel(Long id) throws IOException {
        Hotel hotel = getById(id);
        HotelDoc hotelDoc = new HotelDoc(hotel);
        String jsonString = JSON.toJSONString(hotelDoc);
        IndexRequest request = new IndexRequest("hotel").id(String.valueOf(id));
        request.source(jsonString, XContentType.JSON);
        client.index(request,RequestOptions.DEFAULT);
    }

    @Override
    public void deleteHotel(Long id) throws IOException {
        DeleteRequest request = new DeleteRequest("hotel");
        request.id(String.valueOf(id));
        client.delete(request,RequestOptions.DEFAULT);
    }

    private List<String> getStarName(RequestParam param) throws IOException {
        String key = param.getKey();
        SearchRequest request = new SearchRequest("hotel");
        if (key == null || "".equals(key)){
            request.source().query(QueryBuilders.matchAllQuery()).size(0);
        }else {
            request.source().query(QueryBuilders.matchQuery("name",key)).size(0);
        }
        request.source().aggregation(AggregationBuilders.terms("starName").field("starName"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("starName");
        for (Terms.Bucket bucket : terms.getBuckets()) {
            starName.add(bucket.getKeyAsString());
        }
        return starName;
    }

    private List<String> getCity(RequestParam param) throws IOException {
        String key = param.getKey();
        SearchRequest request = new SearchRequest("hotel");
        if (key == null || "".equals(key)){
            request.source().query(QueryBuilders.matchAllQuery()).size(0);
        }else {
            request.source().query(QueryBuilders.matchQuery("name",key)).size(0);
        }
        request.source().aggregation(AggregationBuilders.terms("city").field("city"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("city");
        for (Terms.Bucket bucket : terms.getBuckets()) {
            city.add(bucket.getKeyAsString());
        }
        return city;
    }

    private List<String> getBrand(RequestParam param) throws IOException {
        String key = param.getKey();
        SearchRequest request = new SearchRequest("hotel");
        if (key == null || "".equals(key)){
            request.source().query(QueryBuilders.matchAllQuery()).size(0);
        }else {
            request.source().query(QueryBuilders.matchQuery("name",key)).size(0);
        }
        request.source().aggregation(AggregationBuilders.terms("brand").field("brand").size(20));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        Terms terms = response.getAggregations().get("brand");
        for (Terms.Bucket bucket : terms.getBuckets()) {
            brand.add(bucket.getKeyAsString());
        }
        return brand;
    }
}
